package com.ysjweb.dish.tool;


import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
//import javax.crypto.spec.PKCS8EncodedKeySpec;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.nio.charset.StandardCharsets;
import java.security.Signature;





public class HeFengApiJwt {
    public static String generateJwt() throws Exception {
// Private key
        String privateKeyString = "MC4CAQAwBQYDK2VwBCIEIGwejqADmb0J+h6ALXDJQSP4nLiPk/oABMf6S/9pCb5p";
        privateKeyString = privateKeyString.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").trim();
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("EdDSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

// Header
        String headerJson = "{\"alg\": \"EdDSA\", \"kid\": \"CKB32MAAN9\"}";

// Payload
        long iat = ZonedDateTime.now(ZoneOffset.UTC).toEpochSecond() - 30;
        long exp = iat + 900;
        String payloadJson = "{\"sub\": \"492FYGQXTR\", \"iat\": " + iat + ", \"exp\": " + exp + "}";

// Base64url header+payload
        String headerEncoded = Base64.getUrlEncoder().encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
        String payloadEncoded = Base64.getUrlEncoder().encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));
        String data = headerEncoded + "." + payloadEncoded;

// Sign
        Signature signer = Signature.getInstance("EdDSA");
        signer.initSign(privateKey);
        signer.update(data.getBytes(StandardCharsets.UTF_8));
        byte[] signature = signer.sign();

        String signatureEncoded = Base64.getUrlEncoder().encodeToString(signature);

        String jwt = data + "." + signatureEncoded;
        return jwt;
    }
}
